package com.education.welco.controller;

import com.education.auth.aspectannotation.BusinessDiary;
import com.education.auth.entity.UserInfo;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.Convert;
import com.education.common.utils.DateUtils;
import com.education.quartz.manage.ScheduleManage;
import com.education.quartz.pojo.ScheduleInfoDto;
import com.education.utils.CronUtils;
import com.education.utils.JwtUtil;
import com.education.welco.feign.MsgClient;
import com.education.welco.feign.userFeign;
import com.education.welco.pojo.*;
import com.education.welco.pojo.vo.ScatalogClassVO;
import com.education.welco.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 理论课堂 信息操作处理
 *
 * @author d
 * @date 2020-05-11
 */
@RestController
@RequestMapping("/sTheoryClassroom")
public class STheoryClassroomController {

    @Autowired
    private ISTheoryClassroomService sTheoryClassroomService;
    @Autowired
    private ISTheoryPartekeService isTheoryPartekeService;//参与教授中间表
    @Autowired
    private ISCatalogClassService catalogClassService; //备课分享班级
    @Autowired
    private ITClassService classService;
    @Autowired
    private ITSchooldeptService schooldeptService;
    @Autowired
    private ITTeacherService teacherService;
    @Autowired
    private userFeign userFeign;
    @Autowired
    private MsgClient msgClient;
    @Autowired
    private ISCatalogMenuService catalogMenuService;
    @Autowired
    private ISResourcesService resourcesService;
    @Autowired
    private ISResourceClassService resourceClassService;
    @Autowired
    private ISCatalogClassTeaService catalogClassTeaService; //在授班级
    @Autowired
    private ISHomewordClassService homewordClassService;
    @Autowired
    private ISCatalogWorkService catalogWorkService;
    @Autowired
    private ISAnsweringService answeringService;
    @Autowired
    private ISQueansClassService queansClassService;
    @Autowired
    private ISCatalogService isCatalogService;
    @Autowired
    private ITEquipmentService tEquipmentService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private ScheduleManage scheduleManage;
    @Autowired
    private OrderPaperService orderPaperService;


    /**
     * 开始直播上课条件判断
     * 开始直播时1.判断时间是否满足2.判断设备是否还在
     *
     * @param id 课堂id
     * @return
     */
    @ApiOperation(value = "开始直播上课条件判断", httpMethod = "GET")
    @GetMapping("/judgeLiveCondition")
    public ApiReturnObject judgeLiveCondition(Integer id) {
        STheoryClassroom sTheoryClassroom = sTheoryClassroomService.selectSTheoryClassroomById(id);
        Date attendTime = sTheoryClassroom.getAttendTime();
        if (attendTime.compareTo(new Date()) > 0) {
            return new ApiReturnObject("201", "未到开课时间!", "未到开课时间!");
        }
        //判断班级下的设备是否还在
        TEquipment tEquipment = new TEquipment();
        tEquipment.setClassroomId(sTheoryClassroom.getClassroomId());
        List<TEquipment> tEquipments = tEquipmentService.selectTEquipmentList(tEquipment);
        if (null == tEquipments || tEquipments.size() == 0) {
            return new ApiReturnObject("201", "当前班级下无绑定设备", "当前班级下无绑定设备");
        }
        //修改课堂状态(直播课的状态)
        STheoryClassroom sTheoryClassroom1 = new STheoryClassroom();
        sTheoryClassroom1.setId(id);
        sTheoryClassroom1.setStatus("1");
        int i = sTheoryClassroomService.updateSTheoryClassroom(sTheoryClassroom1);
        return new ApiReturnObject("200", "开课条件满足", "开课条件满足");
    }

    /**
     * 根据(班级id与当天日期)去查询某一天的教学课表
     *
     * @param pageNum
     * @param pageSize
     * @param teaId       班级id
     * @param toDayString 查询某天的课表 '1997-10-07' 标准参数
     * @return
     */
    @ApiOperation(value = "教师端查询某一天的教学课表", httpMethod = "GET")
    @GetMapping("/selectClassSchedule")
    public ApiReturnObject selectClassSchedule(Integer pageNum, Integer pageSize, Integer teaId, String toDayString, String keyWord) throws Exception {
        if (teaId == null) {
            return new ApiReturnObject("201", "参数缺失", "参数缺失");
        } else {
            //开启分页
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<String> weekDays = DateUtils.getWeekDay();
            Map<String, Object> sdsMap = new HashMap<>();
            List<Integer> integers = new ArrayList<>();
            //1.数量
            for (String weekday : weekDays) {
                List<ScatalogClassVO> sds = isCatalogService.findClassScheduleByTeaId(teaId, weekday, keyWord);
                integers.add(sds.size());
            }
            sdsMap.put("weekdayNum", integers);
            //可能需要日期格式的处理 '1997-10-07'
            String nowString = "";
            try {
                Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(toDayString);
                nowString = new SimpleDateFormat("yyyy-MM-dd").format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            List<ScatalogClassVO> sds = isCatalogService.findClassScheduleByTeaId(teaId, nowString, keyWord);
            //开课时间格式处理  08:00 SimpleDateFormat sdf = new SimpleDateFormat("HH-mm");
            /*关于两个字段判断为一个字段的逻辑处理
            isLz 直播课 还是普通课  （1：开启录制，0不开启录制）
            status 直播课的状态  0 未开始  1直播中 2直播结束
            finalStatus:专业课0 未直播1 直播中2 直播结束(录播)3*/
            for (ScatalogClassVO scatalogClassVO : sds) {
                //处理时间格式
                //第一层判断 (直播课 还是普通课)
                if (scatalogClassVO.getIsLz().equals("1")) {
                    //第二层判断
                    switch (scatalogClassVO.getStatus()) {
                        case "0":
                            scatalogClassVO.setFinalStatus("1");
                            break;
                        case "1":
                            scatalogClassVO.setFinalStatus("2");
                            break;
                        case "2":
                            scatalogClassVO.setFinalStatus("3");
                            break;
                    }
                } else {
                    //设置专业课状态
                    scatalogClassVO.setFinalStatus("0");
                }
            }
            sdsMap.put("course", sds);
            return new ApiReturnObject("200", "查询成功", sdsMap);
        }
    }

    /**
     * 格式化时间
     */
    private List<STheoryClassroom> formatDate(List<STheoryClassroom> list) {
        //格式化开始时间和结束时间
        for (STheoryClassroom theoryClassroom : list) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //课程开始时间
            if (theoryClassroom.getAttendTime() != null) {
                String format = simpleDateFormat.format(theoryClassroom.getAttendTime());
                theoryClassroom.setAttendTimeString(format);
            }
            //课程结束时间
            if (theoryClassroom.getEndTime() != null) {
                String format = simpleDateFormat.format(theoryClassroom.getEndTime());
                theoryClassroom.setEndTimeString(format);
            }
        }
        return list;
    }

    /**
     * 获取该预约课程讲授班级
     */
    public List<STheoryClassroom> getClassString(List<STheoryClassroom> list) {
        //遍历集合，设置班级字符串
        for (STheoryClassroom theoryClassroom : list) {
            //根据课程id 查询班级列表
            List<Integer> classIdList = catalogClassService.selectSCatalogClassByCatalogId(theoryClassroom.getCatalogId());
            //根据id 查询班级名称并进行拼接
            String classNameString = "";
            for (int i = 0; i < classIdList.size(); i++) {
                String className = classService.selectTClassById(classIdList.get(i)).getClassName();
                //不是集合中最后一条
                if (i != classIdList.size() - 1) {
                    classNameString = classNameString + className + ",";
                } else {
                    classNameString = classNameString + className;
                }
            }
            theoryClassroom.setClassNameStrings(classNameString);
        }
        return list;
    }

    /**
     * 查询组织架构下的班级
     */
    @GetMapping("/deptAndClaList")
    public ApiReturnObject deptAndClaList(Integer schoolId) {
        if (schoolId != null) {
            //先查询出部门id集合
            ArrayList<TSchooldept> tSchoolDeptList = new ArrayList<>();
            ArrayList<TSchooldept> arrayList = Lists.newArrayList();
            List<TSchooldept> list = schooldeptService.selectTSchooldeptByPrentId2(schoolId);
            for (TSchooldept tSchooldept : list) {
                List<TSchooldept> tSchooldepts = schooldeptService.selectTSchooldeptByPrentId(tSchooldept.getValue());
                if (tSchooldepts != null && tSchooldepts.size() == 0) {
                    arrayList.add(tSchooldept);
                }
            }
            for (TSchooldept dept : arrayList) {
                //dept.setClassList(Lists.newArrayList());
                //查出班级集合
                List<TClass> classes = classService.selectTClassAllByDeptId(dept.getValue());
                if (classes.size() > 0) {
                    dept.setClassList(classes);
                }
                //组织结构没有班级不返回前台
                if (Objects.nonNull(dept.getClassList())) {
                    tSchoolDeptList.add(dept);
                }
            }
            return new ApiReturnObject("200", "查询成功", tSchoolDeptList);
        }
        return new ApiReturnObject("201", "缺少schoolId", "");
    }


    /**
     * 查找老师所带的直播课堂
     *
     * @param teaUserId
     * @return
     */
    @GetMapping("/teaCourseByTeaId")
    public ApiReturnObject selectTeaCourseListByTeaId(Integer teaUserId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<STheoryClassroom> sTheoryClassroomList = sTheoryClassroomService.selectTeaCourseListByTeaId(teaUserId);
        return new ApiReturnObject("200", "查询成功", new PageInfo<STheoryClassroom>(sTheoryClassroomList));
    }

    /**
     * 查询课堂列表  老师讲授的课程
     *
     * @param userId   老师id
     * @param pageNum
     * @param pageSize
     * @param type     类型
     * @return
     */
    @BusinessDiary(methodUrl = "/listJs", record = "查询理论课堂列表", opeTypeName = "查询", opeTypeValue = "1")
    @GetMapping("/listJs")
    public ApiReturnObject listJs(Integer userId, Integer pageNum, Integer pageSize, String type, String attendpkTime, String endpkTime) {
        if (userId != null) {
            STheoryClassroom sTheoryClassroom = new STheoryClassroom();
            sTheoryClassroom.setUserId(userId);
            sTheoryClassroom.setType(endpkTime);
            sTheoryClassroom.setAttendpkTime(attendpkTime);
            sTheoryClassroom.setType(type);
            //分页
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            //返回页面所需数据  班级名称除外
            List<STheoryClassroom> list = sTheoryClassroomService.selectSTheoryClassroomListOther(sTheoryClassroom);
            //List<STheoryClassroom> list1 = getClassString(list);
            List<STheoryClassroom> sTheoryClassrooms = formatDate(list);//格式时间
            //分页参数添加
            PageInfo<STheoryClassroom> pageInfo = new PageInfo<>(sTheoryClassrooms);
            return new ApiReturnObject("200", "查询成功", pageInfo);
        }
        return new ApiReturnObject("201", "缺少userId", "");
    }

    /**
     * 查询理论课堂列表  我参与的 直接进行观看 使用中间表查找
     */
    @GetMapping("/listCy")
    public ApiReturnObject listCy(Integer userId, Integer pageNum, Integer pageSize) {
        if (userId != null) {
            //取到该教师参与的课堂 id
            List<Integer> tPList = isTheoryPartekeService.selectSTheoryPartekeByUserId(userId);
            HashMap<String, Object> map = new HashMap<>(2);
            if (tPList != null && tPList.size() > 0) {
                map.put("tPList", tPList);
                map.put("userId", userId);
                if (pageNum != null && pageSize != null) {
                    PageHelper.startPage(pageNum, pageSize);
                }
                //返回页面所需数据
                List<STheoryClassroom> sTheoryClassrooms = sTheoryClassroomService.selectSTheoryClassroomListOtherTwo(map);
                //拼接班级字符串
//                List<STheoryClassroom> list = getClassString(sTheoryClassrooms);
                //格式化 开始时间 和 结束时间
                List<STheoryClassroom> sTheoryClassroomsOne = formatDate(sTheoryClassrooms);
//                PageInfo<STheoryClassroom> pageInfo = new PageInfo<>(sTheoryClassroomsOne);
                return new ApiReturnObject("200", "查询成功", sTheoryClassroomsOne);
            }
            //没有参与的课程
            return new ApiReturnObject("201", "该教师没有参与课程", "");
        }
        return new ApiReturnObject("201", "缺少userId", "");
    }

    /**
     * 筛选班级列表  全部班级列表
     *
     * @param attendTimeString
     * @param endTimeString
     * @param teacherId
     * @return
     * @throws ParseException
     */
    @GetMapping("/roomList")
    public ApiReturnObject roomList(String attendTimeString, String endTimeString, Integer teacherId) throws ParseException {
        if (attendTimeString != null && endTimeString != null && teacherId != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //查询出在该时间段内使用的教室 根据选定的 开始时间 和 结束时间
            STheoryClassroom theoryClassroom = new STheoryClassroom();
            theoryClassroom.setAttendTime(simpleDateFormat.parse(attendTimeString));//开始时间
            theoryClassroom.setEndTime(simpleDateFormat.parse(endTimeString));//结束时间
            theoryClassroom.setUserId(teacherId);//老师用户id
            //查询出没有时间交叉的班级(没有被占用)
            List<TClass> cIdList = sTheoryClassroomService.selectSTheoryClassroomListByTimeAndIn(theoryClassroom);
            theoryClassroom.setAttendTime(null);
            theoryClassroom.setEndTime(null);
            //查询出所有班级
            List<TClass> cIdList2 = sTheoryClassroomService.selectSTheoryClassroomListByTimeAndIn(theoryClassroom);
            //占用状态添加
            for (TClass tClass : cIdList2) {
                if (cIdList.contains(tClass)) {
                    tClass.setClassOccupyState(false);
                } else {
                    tClass.setClassOccupyState(true);
                }
            }
            //return new ApiReturnObject("200", "查询成功", tSchoolDeptList);
            return new ApiReturnObject("200", "查询成功", cIdList2);
        }
        return new ApiReturnObject("201", "缺少参数", "");
    }

    /**
     * 预约录制时 教师列表 部门 部门下老师列表
     */
    @GetMapping("/deptAndTeaList")
    public ApiReturnObject deptAndTeaList(TTeacher tTeacher) {
        if (tTeacher != null) {
            UserInfo userInfo = jwtUtil.getInfoFromToken();
            List<TTeacher> tTeachers = teacherService.selectTTeacherList(tTeacher);
            int userId = userInfo.getId().intValue();
            tTeachers = tTeachers.stream().filter(s -> !s.getUserId().equals(userId)).collect(Collectors.toList());
            return new ApiReturnObject("200", "查询成功", tTeachers);
        }
        return new ApiReturnObject("201", "缺少schoolId", "");
    }

    /**
     * 预约详情
     */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer id) {
        if (id != null) {
            STheoryClassroom theoryClassroom = sTheoryClassroomService.selectSTheoryClassroomByIdOther(id);
            //设置参与教师id数组
            STheoryParteke parteke = new STheoryParteke();
            parteke.setTheoryId(theoryClassroom.getId());
            List<STheoryParteke> sTheoryPartekes = isTheoryPartekeService.selectSTheoryPartekeList(parteke);
            if (sTheoryPartekes != null && sTheoryPartekes.size() > 0) {
                ArrayList<Integer> integers = new ArrayList<>();
                for (STheoryParteke sTheoryParteke : sTheoryPartekes) {
                    integers.add(sTheoryParteke.getUserId());
                }
                theoryClassroom.setTeaIdList(integers);
            }
            //格式化 开始时间 和 结束时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //课程开始时间
            if (theoryClassroom.getAttendTime() != null) {
                String format = simpleDateFormat.format(theoryClassroom.getAttendTime());
                theoryClassroom.setAttendTimeString(format);
            }
            //课程结束时间
            if (theoryClassroom.getEndTime() != null) {
                String format = simpleDateFormat.format(theoryClassroom.getEndTime());
                theoryClassroom.setEndTimeString(format);
            }
            return new ApiReturnObject("200", "查询成功", theoryClassroom);
        }
        return new ApiReturnObject("201", "缺少参数", "");

    }

    /**
     * 日排课、周排课、月排课查询
     *
     * @param userId       老师id
     * @param pageNum
     * @param pageSize
     * @param attendpkTime 开始日期
     * @param endpkTime    结束日期
     * @return
     */
    @BusinessDiary(methodUrl = "/selectPaike", record = "查询排课列表", opeTypeName = "查询", opeTypeValue = "1")
    @GetMapping("/selectPaike")
    public ApiReturnObject selectPaike(Integer id, Integer userId, Integer pageNum, Integer pageSize, String attendpkTime, String endpkTime) throws Exception {
        if (userId != null) {
            STheoryClassroom sTheoryClassroom = new STheoryClassroom();
            sTheoryClassroom.setId(id);
            sTheoryClassroom.setUserId(userId);
            sTheoryClassroom.setEndpkTime(endpkTime);
            sTheoryClassroom.setAttendpkTime(attendpkTime);
            //分页
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<STheoryClassroom> list = sTheoryClassroomService.selectPaikeList(sTheoryClassroom);
            if (null != list || list.size() > 0) {
                for (STheoryClassroom theoryClassroom : list) {
                    theoryClassroom.setTeaIdList(Arrays.asList(Convert.toIntArray(",", theoryClassroom.getTeaStr())));
                }
            }
            PageInfo<STheoryClassroom> pageInfo = new PageInfo<>(list);
            return new ApiReturnObject("200", "查询成功", pageInfo);
        }
        return new ApiReturnObject("201", "缺少userId", "");
    }

    /**
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @GetMapping("/selectPaikeTwo")
    public ApiReturnObject selectPaikeTwo(Integer userId, Integer pageNum, Integer pageSize) throws Exception {
        if (userId != null) {
            STheoryClassroom sTheoryClassroom = new STheoryClassroom();
            sTheoryClassroom.setUserId(userId);
            //分页
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<STheoryClassroom> list = sTheoryClassroomService.selectPaikeList(sTheoryClassroom);
            PageInfo<STheoryClassroom> pageInfo = new PageInfo<>(list);
            return new ApiReturnObject("200", "查询成功", pageInfo);
        }
        return new ApiReturnObject("201", "缺少userId", "");
    }

    /**
     * 日排课、周排课、月排课新增
     *
     * @param sTheoryClassroom
     * @return
     * @throws ParseException
     */
    @PostMapping("/addPaike")
    public ApiReturnObject addPaike(@RequestBody STheoryClassroom sTheoryClassroom) throws ParseException {
        //开课时间必须大于当前时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = format.parse(sTheoryClassroom.getAttendpkTime());
        if (new Date().compareTo(parse) >= 0) {
            return new ApiReturnObject("201", "开课时间为过去时间", "");
        }
        if (sTheoryClassroom.getClassroomId() != null && sTheoryClassroom.getAttendpkTime() != null && sTheoryClassroom.getEndpkTime() != null) {
            if (null == sTheoryClassroom.getIsLz()) {
                sTheoryClassroom.setIsLz("0");
            }
            //将字符串日期转换为日期类型
            sTheoryClassroom.setAttendTime(parse);
            sTheoryClassroom.setEndTime(format.parse(sTheoryClassroom.getEndpkTime()));
            long between = (sTheoryClassroom.getEndTime().getTime() - sTheoryClassroom.getAttendTime().getTime()) / 1000;//除以1000是为了转换成秒
            long day1 = between / (24 * 3600);
            long hour1 = between % (24 * 3600) / 3600;
            long minute1 = between % 3600 / 60;
            long second1 = between % 60 / 60;
            sTheoryClassroom.setClassHours(hour1 + "小时" + minute1 + "分钟");
            sTheoryClassroom.setId(null);//自动递增
            /*关于两个字段判断为一个字段的逻辑处理
            isLz 直播课 还是普通课  (1直播课，0普通课)
            status 直播课的状态  0 未开始  1直播中 2直播结束
            finalStatus:专业课0 未直播1 直播中2 直播结束(录播)3*/
            //查找设备id
            TEquipment tEquipment = new TEquipment();
            tEquipment.setClassroomId(sTheoryClassroom.getClassroomId());
            List<TEquipment> tEquipments = tEquipmentService.selectTEquipmentList(tEquipment);
            if (tEquipments.size() != 0) {
                sTheoryClassroom.setEqupmentId(tEquipments.get(0).getEquCode());
            }
            //往数据库添加数据
            sTheoryClassroomService.insertSTheoryClassroom(sTheoryClassroom);
            //是否直播课-添加定时任务修改直播课的结束状态
            //Integer courseId, ScheduleInfoDto dto
            if (sTheoryClassroom.getIsLz().equals("1")) {
                Integer courseId = sTheoryClassroom.getId();
                ScheduleInfoDto scheduleInfoDto = new ScheduleInfoDto();
                scheduleInfoDto.setJobName("job_" + courseId);
                scheduleInfoDto.setJobGroup("LiveStateJobGroup");
                scheduleInfoDto.setTriggerName("trigger_" + courseId);
                scheduleInfoDto.setTriggerGroup("LiveStateTriggerGroup");
                Date endTime = sTheoryClassroom.getEndTime();
                scheduleInfoDto.setCronExpression(CronUtils.getCron(endTime));
                scheduleInfoDto.setJobClassName("com.education.quartz.job.CourseStateJob");
                scheduleManage.addSchedule(courseId, scheduleInfoDto);
            }
            //获取添加的数据生成的主键
            Integer id = sTheoryClassroom.getId();
            //预约课程时选择了参与老师
            if (sTheoryClassroom.getTeaIdList() != null && sTheoryClassroom.getTeaIdList().size() > 0) {
                //获取当前登录人的姓名
                Map<String, Object> map = userFeign.findByUserId(sTheoryClassroom.getUserId());
                //给被选择的老师发布消息   谁邀请的    什么课 开始时间    结束时间
                String content = map.get("name") + "老师邀请您参加" + sTheoryClassroom.getClassroomName() + "课程," +
                        "上课时间为:" + sTheoryClassroom.getAttendTimeString() + "-" + sTheoryClassroom.getEndTimeString();
                String title = "课堂邀请";
                //消息内容   消息标题   消息类型    邀请老师id集合
                msgClient.addSysInfoMsg(title, content, "1", sTheoryClassroom.getTeaIdList(), sTheoryClassroom.getUserId());
                //往中间表添加数据
                STheoryParteke sTheoryParteke = new STheoryParteke();
                //设置课堂id
                sTheoryParteke.setTheoryId(id);
                for (Integer integer : sTheoryClassroom.getTeaIdList()) {
                    sTheoryParteke.setUserId(integer);
                    //中间表加入数据
                    isTheoryPartekeService.insertSTheoryParteke(sTheoryParteke);
                }
            }
            /**
             * 订单demo演示(新增班级和试卷的关联表记录信息)
             * 班级id、课堂id
             */
            addClasPaper(sTheoryClassroom.getClassroomId(), sTheoryClassroom.getCatalogId(), sTheoryClassroom.getUserId());
            return new ApiReturnObject("200", "添加成功", "");
        } else {
            return new ApiReturnObject("201", "缺少参数", "");
        }
    }

    /**
     * 修改日排课、周排课、月排课新增
     *
     * @param sTheoryClassroom
     * @return
     * @throws ParseException
     */
    @PostMapping("/uptPaike")
    public ApiReturnObject uptPaike(@RequestBody STheoryClassroom sTheoryClassroom) throws ParseException {
        if (sTheoryClassroom.getClassroomId() == null || sTheoryClassroom.getAttendpkTime() == null
                || sTheoryClassroom.getEndpkTime() == null || sTheoryClassroom.getId() == null) {
            return new ApiReturnObject("201", "缺少参数", "");
        }
        //传递课堂主键id
        STheoryClassroom sTheoryClassroom1 = sTheoryClassroomService.selectSTheoryClassroomById(sTheoryClassroom.getId());
        if (sTheoryClassroom1.getAttendTime().compareTo(new Date()) <= 0) {
            return new ApiReturnObject("201", "已到上课时间无法编辑", "已到上课时间无法编辑");
        }
        //将字符串日期转换为日期类型
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sTheoryClassroom.setAttendTime(format.parse(sTheoryClassroom.getAttendpkTime()));
        sTheoryClassroom.setEndTime(format.parse(sTheoryClassroom.getEndpkTime()));
        long between = (sTheoryClassroom.getEndTime().getTime() - sTheoryClassroom.getAttendTime().getTime()) / 1000;//除以1000是为了转换成秒
        long day1 = between / (24 * 3600);
        long hour1 = between % (24 * 3600) / 3600;
        long minute1 = between % 3600 / 60;
        long second1 = between % 60 / 60;
        sTheoryClassroom.setClassHours(hour1 + "小时" + minute1 + "分钟");
        //查找设备id 直播课
        if ("1".equals(sTheoryClassroom.getIsLz())) {
            TEquipment tEquipment = new TEquipment();
            tEquipment.setClassroomId(sTheoryClassroom.getClassroomId());
            List<TEquipment> tEquipments = tEquipmentService.selectTEquipmentList(tEquipment);
            sTheoryClassroom.setEqupmentId(tEquipments.get(0).getEquCode());
        }
        //修改课堂数据
        sTheoryClassroomService.updateSTheoryClassroom(sTheoryClassroom);
        //预约课程时选择了参与老师
        isTheoryPartekeService.deleteSTheoryPartekeBytheoryId(sTheoryClassroom.getId());
        if (sTheoryClassroom.getTeaIdList() != null && sTheoryClassroom.getTeaIdList().size() > 0) {
            STheoryParteke sTheoryParteke = new STheoryParteke();
            //设置课堂id
            sTheoryParteke.setTheoryId(sTheoryClassroom.getId());
            for (Integer integer : sTheoryClassroom.getTeaIdList()) {
                sTheoryParteke.setUserId(integer);
                //中间表加入数据
                isTheoryPartekeService.insertSTheoryParteke(sTheoryParteke);
            }
        }
        return new ApiReturnObject("200", "修改成功", "");
    }

    /**
     * 排课时添加班级和课程下试卷的中间关联表(class_paper)
     *
     * @param classId
     * @param catalogId
     * @param teaId
     */
    public void addClasPaper(Integer classId, Integer catalogId, Integer teaId) {
        //获取课程二级目录集合
        List<SCatalogMenu> TwoCataList = selectTwoList(catalogId);
        if (TwoCataList.size() == 0) {
            return;
        }
        //流转换为int集合
        List<Integer> twoIntList = TwoCataList.stream().map(a -> a.getId()).collect(Collectors.toList());
        //根据二级目录查试卷(查询老师准备的某门课程下的全部试题列表)
        List<Integer> paperIdList = orderPaperService.selectpaperIdByLessonIdTwo(twoIntList);
        //班级和课程下试卷的中间关联表擦插入数据
        if (paperIdList != null && paperIdList.size() > 0) {
            //排除重复数据(根据老师id和班级id查找classpaper表得到paper列表id)
            List<Integer> paperIdListFromData = orderPaperService.queryPaperIdByClassIdAndTeaIdFromClassPaper(classId, teaId);
            paperIdList = paperIdList.parallelStream().filter(paperId -> !paperIdListFromData.contains(paperId)).collect(Collectors.toList());
            if (paperIdList != null && paperIdList.size() > 0) {
                int i = orderPaperService.insertClassPaper(classId, paperIdList, teaId);
            }
        }
    }

    /**
     * @param lessonId
     * @return
     */
    public List<SCatalogMenu> selectTwoList(Integer lessonId) {
        SCatalogMenu sCatalogMenu = new SCatalogMenu();
        //查询出第1级列表
        sCatalogMenu.setParentId(0);
        sCatalogMenu.setId(lessonId);
        SCatalogMenu list = catalogMenuService.selectSCatalogMenuList2(sCatalogMenu);
        //二级 以及 下面子列表
        return listSon22(list);
    }

    //查询目录列表
    public List<SCatalogMenu> listSon22(SCatalogMenu cList) {
        //根据课程id查询出一级目录列表jrCatalogs
        List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(cList.getId());
        if (jrCatalogs != null && jrCatalogs.size() > 0) {
            //cList.setChildren(listSon(jrCatalogs));
            return listSon11(jrCatalogs);
        }
        return null;
    }

    public List<SCatalogMenu> listSon11(List<SCatalogMenu> cList) {
        List<SCatalogMenu> twoSCatalogMenu = new ArrayList<>();
        for (SCatalogMenu catalogMenu : cList) {
            //根据第一级的id查询出二级列表
            List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(catalogMenu.getId());
            //二级列表汇总
            twoSCatalogMenu.addAll(jrCatalogs);
            if (jrCatalogs != null && jrCatalogs.size() > 0) {
                //设置子级集合
                //catalogMenu.setChildren(listSon(jrCatalogs));
                //catalogMenu.setChildren(jrCatalogs);
            }
        }
        return twoSCatalogMenu;
    }

    /**
     * 新增保存理论课堂
     */
    @Transactional
    @PostMapping("/add")
    public ApiReturnObject addSave(@RequestBody STheoryClassroom sTheoryClassroom) throws ParseException {
        //添加之前先进行查询  根据指定时间以及教室id 判断该教师是否被占用 大于开始时间 小于结束时间
        if (sTheoryClassroom.getClassroomId() != null && sTheoryClassroom.getAttendTimeString() != null && sTheoryClassroom.getEndTimeString() != null) {
            //将字符串日期转换为日期类型
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sTheoryClassroom.setAttendTime(format.parse(sTheoryClassroom.getAttendTimeString()));
            sTheoryClassroom.setEndTime(format.parse(sTheoryClassroom.getEndTimeString()));
            long between = (sTheoryClassroom.getEndTime().getTime() - sTheoryClassroom.getAttendTime().getTime()) / 1000;//除以1000是为了转换成秒
            long day1 = between / (24 * 3600);
            long hour1 = between % (24 * 3600) / 3600;
            long minute1 = between % 3600 / 60;
            long second1 = between % 60 / 60;
            System.out.println(hour1 + "小时" + minute1 + "分钟");
            sTheoryClassroom.setClassHours(hour1 + "小时" + minute1 + "分钟");
            //判断是否存在重叠的时间段
            List<STheoryClassroom> sTheoryClassrooms = sTheoryClassroomService.selectSTheoryClassroomListByClassroomAndTime(sTheoryClassroom);
            if (sTheoryClassrooms != null && sTheoryClassrooms.size() > 0) {
                return new ApiReturnObject("201", "该时间段已有排课", "");
            } else {
                //进行添加
                if (sTheoryClassroom.getId() != null) {
                    sTheoryClassroom.setId(null);
                }
                //保存 在授班级
                if (sTheoryClassroom.getClassroomId() != null) {
                    SCatalogClassTea sCatalogClassTea = new SCatalogClassTea();
                    sCatalogClassTea.setUserId(sTheoryClassroom.getUserId());
                    sCatalogClassTea.setCatalogId(sTheoryClassroom.getCatalogId());
                    sCatalogClassTea.setCreateTime(new Date());
                    sCatalogClassTea.setClassId(sTheoryClassroom.getClassroomId());
                    catalogClassTeaService.insertSCatalogClassTea(sCatalogClassTea);
                }
                //往数据库添加数据
                sTheoryClassroomService.insertSTheoryClassroom(sTheoryClassroom);
                //所有二级目录id
                List<Integer> idlist = new ArrayList<>();
                SCatalogMenu sCatalogMenu = new SCatalogMenu();
                //查询出第一级列表
                sCatalogMenu.setParentId(0);
                sCatalogMenu.setId(sTheoryClassroom.getCatalogId());
                SCatalogMenu list = catalogMenuService.selectSCatalogMenuList2(sCatalogMenu);
                //根据第一级的id查询出下级列表
                SCatalogMenu sCatalogMenus = listSon2(list);
                List<SCatalogMenu> children1 = sCatalogMenus.getChildren();
                for (int i = 0; i < children1.size(); i++) {
                    List<SCatalogMenu> children = children1.get(i).getChildren();
                    for (int j = 0; j < children.size(); j++) {
                        idlist.add(children.get(i).getId());
                    }
                }
                if (idlist.size() > 0) {
                    //拿到所有的二级目录id下的所有资源(1,7,5教学课件，微课，真人实操资源)
                    SResources sResources = new SResources();
                    sResources.setIdlist(idlist);
                    sResources.setType1("1");
                    //所有该课程下二级目录的资源数据
                    List<SResources> sResourceList = resourcesService.selectSResourcesList(sResources);
                    List<Integer> idall = new ArrayList<>();
                    List<SResourceClass> resourceClassList = new ArrayList<>();
                    for (SResources one : sResourceList) {
                        resourceClassService.deleteSResourceClassByresourceId(one.getId());
                        SResourceClass resourceClass = new SResourceClass();
                        resourceClass.setResourceId(one.getId());
                        resourceClass.setCreateTime(new Date());
                        resourceClass.setClassId(sTheoryClassroom.getClassroomId());
                        resourceClassList.add(resourceClass);
                        idall.add(one.getId());
                    }
                    //批量新增中间表数据
                    resourceClassService.insertSResourceClassList(resourceClassList);

                    //拿到所有的二级目录id下的所有资源(4,2图片，课前预习)
                    SResources sResources1 = new SResources();
                    sResources1.setIdlist(idlist);
                    sResources1.setType1("2");
                    //所有该课程下二级目录的资源数据
                    List<SResources> sResourceList1 = resourcesService.selectSResourcesList(sResources1);
                    List<SResourceClass> resourceClassList1 = new ArrayList<>();
                    for (SResources one : sResourceList1) {
                        resourceClassService.deleteSResourceClassByresourceId(one.getId());
                        SResourceClass resourceClass = new SResourceClass();
                        resourceClass.setResourceId(one.getId());
                        resourceClass.setCreateTime(new Date());
                        resourceClass.setClassId(sTheoryClassroom.getClassroomId());
                        resourceClassList1.add(resourceClass);
                        //resourceClassService.insertSResourceClass(resourceClass);
                    }
                    //批量推送
                    resourceClassService.insertSResourceClassList(resourceClassList1);

                    //课后作业所有数据
                    SCatalogWork sCatalogWork = new SCatalogWork();
                    sCatalogWork.setIdlist(idlist);
                    List<SHomewordClass> sHomewordClassList = new ArrayList<>();
                    List<SCatalogWork> sCatalogWorks = catalogWorkService.selectSCatalogWorkList(sCatalogWork);
//                    List<SCatalogWork> sCatalogWorks = catalogWorkService.selectSCatalogWorkAllList(sCatalogWork);
                    for (SCatalogWork one : sCatalogWorks) {
                        SHomewordClass homewordClass = new SHomewordClass();
                        homewordClass.setWorkId(one.getId());
                        //先删除中间表数据
                        homewordClassService.deleteSHomewordClassByCatalogId(one.getId());
                        homewordClass.setCreateTime(new Date());
                        homewordClass.setClassId(sTheoryClassroom.getClassroomId());
                        sHomewordClassList.add(homewordClass);
//                        homewordClassService.insertSHomewordClass(homewordClass);
                    }
                    //批量添加关系表
                    homewordClassService.insertSHomewordClassList(sHomewordClassList);

                    //答疑推送数据
                    SAnswering sAnswering = new SAnswering();
                    sAnswering.setIdlist(idlist);
                    List<SAnswering> sAnswerings = answeringService.selectSAnsweringList(sAnswering);
                    List<SQueansClass> sQueansClassList = new ArrayList<>();
                    for (SAnswering one : sAnswerings) {
                        SQueansClass queansClass = new SQueansClass();
                        queansClass.setAnsweringId(one.getId());
                        //先删除中间表数据
                        queansClassService.deleteSQueansClassByCatalogId(one.getId());
                        queansClass.setCreateTime(new Date());
                        queansClass.setClassId(sTheoryClassroom.getClassroomId());
                        sQueansClassList.add(queansClass);
                        //queansClassService.insertSQueansClass(queansClass);

                    }
                    //批量添加关系表
                    queansClassService.insertSQueansClassList(sQueansClassList);
                }

                //获取添加的数据生成的主键
                Integer id = sTheoryClassroom.getId();
                //预约课程时选择了参与老师
                if (sTheoryClassroom.getTeaIdList() != null && sTheoryClassroom.getTeaIdList().size() > 0) {
                    //获取当前登录人的姓名
                    Map<String, Object> map = userFeign.findByUserId(sTheoryClassroom.getUserId());
                    //给被选择的老师发布消息   谁邀请的    什么课 开始时间    结束时间
                    String content = map.get("name") + "老师邀请您参加" + sTheoryClassroom.getClassroomName() + "课程," +
                            "上课时间为:" + sTheoryClassroom.getAttendTimeString() + "-" + sTheoryClassroom.getEndTimeString();
                    String title = "课堂邀请";
                    //消息内容   消息标题   消息类型    邀请老师id集合
                    msgClient.addSysInfoMsg(title, content, "1", sTheoryClassroom.getTeaIdList(), sTheoryClassroom.getUserId());
                    //往中间表添加数据
                    STheoryParteke sTheoryParteke = new STheoryParteke();
                    //设置课堂id
                    sTheoryParteke.setTheoryId(id);
                    for (Integer integer : sTheoryClassroom.getTeaIdList()) {
                        sTheoryParteke.setUserId(integer);
                        //中间表加入数据
                        isTheoryPartekeService.insertSTheoryParteke(sTheoryParteke);
                    }
                }
                return new ApiReturnObject("200", "添加成功", "");
            }
        }
        return new ApiReturnObject("201", "缺少参数", "");
    }


    //查询目录列表
    public SCatalogMenu listSon2(SCatalogMenu cList) {
        //根据第一级的id查询出下级列表
        List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(cList.getId());
        if (jrCatalogs != null && jrCatalogs.size() > 0) {
            //设置子级集合
            cList.setChildren(listSon(jrCatalogs));
        }
        return cList;
    }


    //查询目录列表
    public List<SCatalogMenu> listSon(List<SCatalogMenu> cList) {
        for (SCatalogMenu catalogMenu : cList) {
            //根据第一级的id查询出下级列表
            List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(catalogMenu.getId());
            if (jrCatalogs != null && jrCatalogs.size() > 0) {
                //设置子级集合
                catalogMenu.setChildren(listSon(jrCatalogs));
            }
        }
        return cList;
    }

    /**
     * 日排课、周排课、月排课修改
     *
     * @param sTheoryClassroom
     * @return
     */
    @PostMapping("/update")
    public ApiReturnObject editSave(@RequestBody STheoryClassroom sTheoryClassroom) {
        if (sTheoryClassroom.getId() != null) {
            //预约课程时选择了参与老师
            if (sTheoryClassroom.getTeaIdList() != null && sTheoryClassroom.getTeaIdList().size() > 0) {
                //先删除中间表数据
                isTheoryPartekeService.deleteSTheoryPartekeBytheoryId(sTheoryClassroom.getId());
                //往中间表添加数据
                STheoryParteke sTheoryParteke = new STheoryParteke();
                //设置课堂id
                sTheoryParteke.setTheoryId(sTheoryClassroom.getId());
                for (Integer integer : sTheoryClassroom.getTeaIdList()) {
                    sTheoryParteke.setUserId(integer);
                    //中间表加入数据
                    isTheoryPartekeService.insertSTheoryParteke(sTheoryParteke);
                }
            }
            sTheoryClassroomService.updateSTheoryClassroom(sTheoryClassroom);
            return new ApiReturnObject("200", "修改成功", "");
        }
        return new ApiReturnObject("201", "缺少参数", "");
    }


    /**
     * 直播课添加录播视频url
     *
     * @param sTheoryClassroom
     * @return
     */
    @PostMapping("/updateRecordedAddress")
    public ApiReturnObject updateRecordedAddress(@RequestBody STheoryClassroom sTheoryClassroom) {
        sTheoryClassroomService.updateSTheoryClassroom(sTheoryClassroom);
        return new ApiReturnObject("200", "修改成功", "");
    }


    /**
     * 课堂修改状态
     */
    @PostMapping("/updateStatus")
    public ApiReturnObject updateStatus(@RequestBody STheoryClassroom sTheoryClassroom) {
        /** 0 未开始  1直播中 2直播结束 */
        String status = sTheoryClassroom.getStatus();
        Integer id = sTheoryClassroom.getId();
        STheoryClassroom theoryClassroom = sTheoryClassroomService.selectSTheoryClassroomById(id);
        if ("1".equals(status)) {
            /** 上课时间 */
            Date attendTime = theoryClassroom.getAttendTime();
            /** 结束时间 */
            Date endTime = theoryClassroom.getEndTime();
            Date nowDate = new Date();
            if (nowDate.getTime() >= attendTime.getTime() && nowDate.getTime() < endTime.getTime()) {
                sTheoryClassroomService.updateSTheoryClassroom(sTheoryClassroom);
                return new ApiReturnObject("200", "修改成功", "");
            } else if (nowDate.getTime() >= endTime.getTime()) {
                sTheoryClassroom.setStatus("2");
                sTheoryClassroomService.updateSTheoryClassroom(sTheoryClassroom);
                return new ApiReturnObject("300", "直播已结束", "");
            } else {
                return new ApiReturnObject("300", "直播还未开始", "");
            }
        } else {
            sTheoryClassroomService.updateSTheoryClassroom(sTheoryClassroom);
            return new ApiReturnObject("200", "修改成功", "");
        }
    }

    /**
     * 日排课、周排课、月排课删除
     * 删除条件-开课之前可以删除
     * id
     *
     * @param sTheoryClassroom
     * @return
     */
    @PostMapping("/del")
    @Transactional
    public ApiReturnObject remove(@RequestBody STheoryClassroom sTheoryClassroom) {
        //传递课堂主键id
        STheoryClassroom sTheoryClassroom1 = sTheoryClassroomService.selectSTheoryClassroomById(sTheoryClassroom.getId());
        if (sTheoryClassroom1.getAttendTime().compareTo(new Date()) <= 0) {
            return new ApiReturnObject("201", "已到上课时间无法删除", "已到上课时间无法删除");
        }
        if (sTheoryClassroom.getId() != null) {
            //先删除理论课堂参与教师表中数据
            isTheoryPartekeService.deleteSTheoryPartekeBytheoryId(sTheoryClassroom.getId());//参与者
            int i = sTheoryClassroomService.deleteSTheoryClassroomById(sTheoryClassroom.getId());//课堂表
            return new ApiReturnObject("200", "删除成功", "");
        }
        return new ApiReturnObject("201", "缺少参数", "");
    }
}